package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pari.Pari;
import pari.PariHistorique;

import com.cedarsoftware.util.io.JsonWriter;

import dao.DaoPariHistorique;
import externaldata.gareSelection.GareSelection;
import servlet.utilities.Paris_S;
import user.User;


public class S_Bets extends HttpServlet {
	private static final long serialVersionUID = 1L;


	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	//@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("json");
		PrintWriter out = response.getWriter();
		User user = (User) request.getSession().getAttribute("user");
		List<Pari> paris = user.getParis();
		DaoPariHistorique daoParisHistorique = new DaoPariHistorique();
		List<PariHistorique> paris_historique = daoParisHistorique.getBetsHistory(user.getMail());
		List<List<Paris_S>> json = new ArrayList<List<Paris_S>>();
		if(paris != null && !paris.isEmpty()) {
			List<GareSelection> selection = (List<GareSelection>) request.getAttribute("gares_selection");
			List<Paris_S> json_p = new ArrayList<Paris_S>();
			for(Pari p : paris) {
				Paris_S ps = new Paris_S();
				ps.update(selection, p);
				json_p.add(ps);
			}
			json.add(json_p);
		}
		else {
			json.add(new ArrayList<Paris_S>());
		}
		if(paris_historique != null && !paris_historique.isEmpty()) {
			List<GareSelection> selection = (List<GareSelection>) request.getAttribute("gares_selection");
			List<Paris_S> json_ph = new ArrayList<Paris_S>();
			for(PariHistorique p : paris_historique) {
				Paris_S ps = new Paris_S();
				ps.update(selection, p);
				json_ph.add(ps);
			}
			json.add(json_ph);
		}
		else {
			json.add(new ArrayList<Paris_S>());
		}
		System.out.println("\t\t\t\tS_Bets\n" + JsonWriter.objectToJson(json));
		out.print(JsonWriter.objectToJson(json));
		out.close();
	}
}